package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NavServiceImpl implements INavService {
    @Override
    public List<NavModel> getNavList() {
        /**
         * 判断数据库的数据来源
         * 1.如果缓存有，则取缓存
         * 2.如果没有，则取数据库
         *
         */
//        final List<NavModel>[] list = new List[]{new ArrayList<>()};
//        for (int i = 0; i < 1000; i++) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    list[0] = getListForThread();
//                }
//            }, "綫程" + i).start();
//
//        }

        return getListForThread();
    }

    private synchronized List<NavModel> getListForThread() {
        Jedis jedis = new Jedis();
        List<NavModel> list = new ArrayList<>();
        long length = jedis.llen("navTitle");
        if (length > 0) {
            List<String> navTitle = jedis.lrange("navTitle", 0, length);
            List<String> navHref = jedis.lrange("navHref", 0, length);
            for (int i = 0; i < length; i++) {
                NavModel model = new NavModel();
                model.setTitle(navTitle.get(i));
                model.setHref(navHref.get(i));
                list.add(model);
            }
            System.out.println("huancun" + Thread.currentThread().getName());
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.getNavModelList();
//            将数据存放在缓存里面

            for (NavModel model :
                    list) {
                jedis.rpush("navTitle", model.getTitle());
                jedis.rpush("navHref", model.getHref());

            }
            System.out.println("mysql" + Thread.currentThread().getName());
        }
        return list;
    }

    @Override
    public int add(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int count = navDao.update(navModel);
        if (count == 1) {
            Jedis jedis = new Jedis();
            jedis.del("navTitle");
        }
        return count;
    }

    /**
     * 1.引入jar包
     * 2.在服务逻辑层修改
     * 3.判断缓存里面是否有值
     *  有，取缓存的值，封装成需要的对象
     *  没有，则取数据库
     * 4.修改时，需要手动取删除缓存的key值
     */
}
